package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IRegisterService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Author: ZaiRiChangYe
 * @Date: 2020/5/11 15:53
 * @Description: 用户注册具体逻辑
 */
@Service
@Slf4j
public class RegisterServiceImpl implements IRegisterService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private UserVerifyMapper userVerifyMapper;

    @Autowired
    private JavaMailSender mailSender;

    @Override
    public UserRegisterResponse register(UserRegisterRequest registerRequest) {

        UserRegisterResponse response = new UserRegisterResponse();

        // 判空驗證
        registerRequest.requestCheck();

        // 驗證用戶名是否重複 -- 直接寫個方法
        volidUserNameRepeat(registerRequest);

        // 1. 向⽤户表中插⼊⼀条记录 -- username不可以重複
        Member member = new Member();
        member.setUsername(registerRequest.getUserName());
        member.setEmail(registerRequest.getEmail());

        // password需要加密处理
        String password = DigestUtils.md5DigestAsHex(registerRequest.getUserPwd().getBytes());
        member.setPassword(password);

        member.setCreated(new Date());
        member.setUpdated(new Date());
        member.setIsVerified("N");
        member.setState(1);

        int effectRows = memberMapper.insert(member);
        if (effectRows != 1){
            response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
            return response;
        }

        // 2. 向⽤户验证表中插⼊⼀条记录
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(member.getUsername());
        userVerify.setIsVerify(member.getIsVerified());
        String key = member.getUsername() + member.getPassword() + UUID.randomUUID().toString();
        String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
        userVerify.setUuid(uuid);
        userVerify.setRegisterDate(new Date());
        userVerify.setIsExpire("N");
        userVerify.setIsVerify("N");

        int rows = userVerifyMapper.insert(userVerify);
        if (rows != 1){
            response.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
            return response;
        }

        // 3. 发送用户激活邮件 -- 直接写一个发送邮件的方法 -- 需要访问用户激活的接口
        // TODO 發送用戶激活郵件 -- 激活邮件应该是一个链接， 哟一个接口去处理用户的激活 -- 消息中间件MQ（异步化）
        sendEmail(uuid,registerRequest);

        // 打印日志
        log.info("用戶注冊成功，注冊參數request:{},{}", JSON.toJSONString(registerRequest),"1x2x3x");
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return response;
    }

    /**
     * 这是一个发送用户激活邮件的方法
     */
    private void sendEmail(String uuid, UserRegisterRequest registerRequest) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("【不是垃圾】此为GPmall激活用户账号邮件");
        message.setFrom("zairichangye@163.com");
        message.setTo(registerRequest.getEmail());
        // 用戶激活地址 -- 就是那個鏈接地址
        StringBuilder builder = new StringBuilder();
        builder.append("http://localhost:8080/user/verify?uid=").append(uuid).append("&username=").append(registerRequest.getUserName());
        // http://localhost:8080/user/verify?uid=xxx&username=xxxx
        message.setText(builder.toString());

        mailSender.send(message);
    }

    /**
     * 驗證用戶名是否重複
     * @param registerRequest
     * 因为该方法返回的是void，所以可以用来抛异常进行处理
     */
    private void volidUserNameRepeat(UserRegisterRequest registerRequest) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username",registerRequest.getUserName());

        // 实际上的SQL语句：select * from tb_member where username = #{username}
        List<Member> memberList = memberMapper.selectByExample(example);

        // 判断list是否为空，为空说明用户名还未被注册过，不为空说明用户名已经存在
        if(!CollectionUtils.isEmpty(memberList)){
            throw new ValidateException(
                    SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(),
                    SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
        }
    }
}
